<?php

namespace RjYst\ExcelExport\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;
use RjYst\ExcelExport\Services\PackageChecker;

class UpdateExcelExportCommand extends Command
{
    protected $signature = 'rj:update-excel-export {--force : 强制覆盖已存在的文件}';
    protected $description = 'Update RjYst Excel Export Package with ClickLearn support';

    public function handle()
    {
        $this->info('📊 开始更新 RjYst Excel Export Package...');

        if (!$this->option('force')) {
            if (!$this->confirm('确定要更新 Excel Export 扩展包吗？这将添加 ClickLearn 导出支持！')) {
                $this->info('更新已取消');
                return;
            }
        }

        // 1. 发布配置文件
        $this->publishConfig();

        // 2. 创建导出文件
        $this->createExportFiles();

        // 3. 更新控制器
        $this->updateExportController();

        // 4. 创建 ClickLearn Action
        $this->createClickLearnDataExportAction();

        // 5. 完成提示
        $this->displaySuccessMessage();
    }

    protected function publishConfig()
    {
        $this->info('⚙️ 发布配置文件...');

        $this->call('vendor:publish', [
            '--tag' => 'rj-excel-export-config',
            '--force' => $this->option('force')
        ]);

        $this->info('✅ 配置文件发布完成');
    }

    protected function createExportFiles()
    {
        $this->info('📝 创建导出文件...');

        // 创建 ClickLearnSheet
        $this->createClickLearnSheet();

        // 创建 ClickLearnSpellSheet
        $this->createClickLearnSpellSheet();

        // 创建 ClickLearnExport
        $this->createClickLearnExport();
    }

    protected function createClickLearnSheet()
    {
        $sheetPath = app_path('Admin/Exports/Sheet');
        $sheetFile = $sheetPath . '/ClickLearnSheet.php';

        // 确保目录存在
        PackageChecker::ensureDirectoryExists($sheetPath);

        // 检查文件是否存在
        if (PackageChecker::fileExists($sheetFile) && !$this->option('force')) {
            $this->info('ℹ️ ClickLearnSheet.php 已存在，跳过创建');
            return;
        }

        $this->copyTemplateFile('ClickLearnSheet.php', $sheetFile);
        $this->info('✅ 创建文件: ClickLearnSheet.php');
    }

    protected function createClickLearnSpellSheet()
    {
        $sheetPath = app_path('Admin/Exports/Sheet');
        $sheetFile = $sheetPath . '/ClickLearnSpellSheet.php';

        // 确保目录存在
        PackageChecker::ensureDirectoryExists($sheetPath);

        // 检查文件是否存在
        if (PackageChecker::fileExists($sheetFile) && !$this->option('force')) {
            $this->info('ℹ️ ClickLearnSpellSheet.php 已存在，跳过创建');
            return;
        }

        $this->copyTemplateFile('ClickLearnSpellSheet.php', $sheetFile);
        $this->info('✅ 创建文件: ClickLearnSpellSheet.php');
    }

    protected function createClickLearnExport()
    {
        $exportPath = app_path('Admin/Exports');
        $exportFile = $exportPath . '/ClickLearnExport.php';

        // 确保目录存在
        PackageChecker::ensureDirectoryExists($exportPath);

        // 检查文件是否存在
        if (PackageChecker::fileExists($exportFile) && !$this->option('force')) {
            $this->info('ℹ️ ClickLearnExport.php 已存在，跳过创建');
            return;
        }

        $this->copyTemplateFile('ClickLearnExport.php', $exportFile);
        $this->info('✅ 创建文件: ClickLearnExport.php');
    }

    protected function updateExportController()
    {
        $this->info('🎮 更新导出控制器...');

        $controllerPath = app_path('Admin/Controllers/Export');
        $controllerFile = $controllerPath . '/ExcelExportController.php';

        // 确保目录存在
        PackageChecker::ensureDirectoryExists($controllerPath);

        // 直接覆盖更新控制器
        $this->copyTemplateFile('ExcelExportController.php', $controllerFile);
        $this->info('✅ 更新文件: ExcelExportController.php');
    }

    protected function createClickLearnDataExportAction()
    {
        $this->info('⚡ 创建 ClickLearn 数据导出 Action...');

        $actionPath = app_path('Admin/Actions/Data');
        $actionFile = $actionPath . '/DataExport.php';

        // 确保目录存在
        PackageChecker::ensureDirectoryExists($actionPath);

        // 检查文件是否存在
        if (PackageChecker::fileExists($actionFile) && !$this->option('force')) {
            $this->info('ℹ️ Data/DataExport.php 已存在，跳过创建');
            return;
        }

        $this->copyTemplateFile('DataDataExport.php', $actionFile);
        $this->info('✅ 创建文件: Data/DataExport.php');
    }

    protected function copyTemplateFile(string $templateName, string $destination)
    {
        $templatePath = __DIR__ . '/../../Templates/' . $templateName;

        if (File::exists($templatePath)) {
            File::copy($templatePath, $destination);
        } else {
            $this->warn("⚠️ 模板文件不存在: {$templateName}");
        }
    }

    protected function displaySuccessMessage()
    {
        $this->info('🎉 RjYst Excel Export Package 更新完成！');
        $this->line('');
        $this->line('📁 新增/更新的文件：');
        $this->line('   - app/Admin/Exports/Sheet/ClickLearnSheet.php');
        $this->line('   - app/Admin/Exports/Sheet/ClickLearnSpellSheet.php');
        $this->line('   - app/Admin/Exports/ClickLearnExport.php');
        $this->line('   - app/Admin/Controllers/Export/ExcelExportController.php (已更新)');
        $this->line('   - app/Admin/Actions/Data/DataExport.php');
        $this->line('   - config/rj-excel-export.php');
        $this->line('');
        $this->line('📦 新增导出功能：');
        $this->line('   - ClickLearn 资源内容导出');
        $this->line('   - ClickLearnSpell 拼写变色导出');
        $this->line('');
        $this->line('🔗 支持的导出路由：');
        $this->line('   - GET /admin/dataExport?uri=/skuCategoryExport');
        $this->line('   - GET /admin/dataExport?uri=/CategoryModule');
        $this->line('   - GET /admin/dataExport?uri=/ClickLearnExport');
        $this->line('');
        $this->line('💡 使用方法：');
        $this->line('   在 ClickLearnController 的 grid 方法中添加：');
        $this->line('   $grid->tools(new \\App\\Admin\\Actions\\Data\\DataExport(\'导出资源内容\', \'/ClickLearnExport\'));');
        $this->line('');
        $this->line('🔧 配置文件：');
        $this->line('   编辑 config/rj-excel-export.php 进行自定义配置');
        $this->line('');
        $this->warn('⚠️ 注意事项：');
        $this->warn('   1. 确保 ClickLearn 和 ClickLearnSpell 模型路径正确');
        $this->warn('   2. 根据需要调整导出字段和格式');
        $this->warn('   3. ExcelExportController 已更新，包含所有导出类型');
    }
}
